from querier.esquerier import ElasticSearchQuerier
import querier.weibo.utils as utils


class WechatUserInfoAnalysisQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type):
        super(WechatUserInfoAnalysisQuerier, self).__init__(es, index, doc_type)

    def _build_query(self, args):
        filters = args.get('filters')
        field = args.get('field')
        query = self._gen_query(filters, field)
        return query, {}, {'filters': filters}

    def _build_result(self, es_result, param):
        # total = es_result['hits']['total']
        agg = es_result['aggregations']
        data = extract_result(agg)
        return {
            "values": {
                'user_counts': data['doc_counts'],
            }
        }

    @staticmethod
    def _gen_query(filters, field):
        filter_clause = []
        filter_clause = utils.add_filter_clause2(filter_clause, filters, 'biz_code', 'must')
        query = {
            "query": {
                "bool": {
                    "filter": filter_clause
                }
            },
            "aggs": {
                "user_hist": {
                    "terms": {
                        'field': field,
                    },
                    # "aggs": {
                    #     "fans_count": {"sum": {"field": "likes", "missing": 0}}
                    # }
                }
            },

            "size": 0
        }
        return query


def extract_result(agg):
    buckets = agg['user_hist']['buckets']

    doc_counts = dict()
    # fans_count = dict()
    for b in buckets:
        k = b['key']
        doc_counts[k] = b['doc_count']
        # fans_count[k] = b['fans_count']['value']

    sorted_keys = sorted(doc_counts.keys())
    return {
        'doc_counts': [{'key': k, 'value': doc_counts[k]} for k in sorted_keys],
        # 'fans_count': [{'key': k, 'value': fans_count[k]} for k in sorted_keys],
    }
